/*
Copyright (C) 2009-2010 Xanadu Development Team

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; version 2
of the License.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "../scripting/AngelScriptEngine.h"
#include "../provider/DataProvider.h"
#include "../tools/PacketCreator.h"
#include "Map.h"
#include "MapDrops.h"
#include "Reactor.h"
#include "../client/ReactorData.h"
#include "../client/ReactorsData.h"
#include "../client/ReactorStateData.h"

void Reactor::hit(Player* player, short stance, char pos) {
	char type = DataProvider::getInstance()->getReactorType(rid, state);
	//type 2 = only hit from right (kerning swamp plants), 00 is air left 02 is ground left
	if((type == 2 && stance != 2) || type != 2) {
		int newstance = DataProvider::getInstance()->getReactorNextState(rid, state);
		if(newstance == -1) {
			return;
		}
		//get next state
		state = newstance;
		int nstate = DataProvider::getInstance()->getReactorNextState(rid, state);
		if(nstate == -1) { //end of reactor
			if(type < 100) { //reactor broken
				destroyed = true;
			}
			else { //item-triggered on final step
				map->send(PacketCreator().updateReactor(this, stance));
			}
			AngelScriptEngine::handleReactor(player, this);
		}
		else { //reactor not broken yet
			map->send(PacketCreator().updateReactor(this, stance), player);
			if(nstate == state) { //current state = next state, looping reactor
				AngelScriptEngine::handleReactor(player, this);
			}
		}
	}
}

void Reactor::setState(int s) {
	ReactorData* r = ReactorsData::getInstance()->getDataByID(rid);
	if(r == NULL)
		return;
	ReactorStateData* sd = r->getDataByID(s);
	if(sd == 0)
		return;
	state = s;
	map->send(PacketCreator().updateReactor(this, 0));
	if(r->getDataByID(s+1) == 0) { // last
		AngelScriptEngine::handleReactor(0, this);
	}
}

void Reactor::drop(Player* player) {
	map->getDrops()->dropFromReactor(this, player);
}

bool Reactor::inArea(Position fpos) {
	Position lt = DataProvider::getInstance()->getReactorLT(rid, state);
	Position rb = DataProvider::getInstance()->getReactorRB(rid, state);
	return fpos.x > pos.x + lt.x && fpos.y > pos.y + lt.y && fpos.x < pos.x + rb.x && fpos.y < pos.y + rb.y;
}